/*
 *  Copyright (C) 2010 glauco
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.balisunrise.nbpam;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle;
import org.balisunrise.application.Application;
import org.balisunrise.application.Module;
import org.balisunrise.nbpam.components.ModulePanel;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.balisunrise.nbpam//Application//EN",
autostore = false)
public final class ApplicationTopComponent extends TopComponent {

    private static ApplicationTopComponent instance;
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "org/balisunrise/nbpam/dir1.png";
    private static final String PREFERRED_ID = "ApplicationTopComponent";

    private Module[] modules;

    public ApplicationTopComponent() {
        modules = Application.get().getModules();
        initComponents();
        addComponents();
        setName(NbBundle.getMessage(ApplicationTopComponent.class,
                "CTL_ApplicationTopComponent"));
        setToolTipText(NbBundle.getMessage(ApplicationTopComponent.class,
                "HINT_ApplicationTopComponent"));
        setIcon(ImageUtilities.loadImage(ICON_PATH, true));

        putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
        //putClientProperty(TopComponent.PROP_SLIDING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
    }

    public int getModulesCount(){
        return modules.length;
    }

    public void refresh(){
        removeAll();
        modules = Application.get().getModules();

        List<ModulePanel> components = new ArrayList<ModulePanel>();
        for (Module module : modules) {
            components.add(new ModulePanel(module));
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);

        GroupLayout.ParallelGroup h = layout.createParallelGroup(
                GroupLayout.Alignment.LEADING);
        for (ModulePanel mp : components) {
            h.addComponent(mp,
                    GroupLayout.DEFAULT_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    Short.MAX_VALUE);
        }

        GroupLayout.SequentialGroup v = layout.createSequentialGroup();
        boolean first = true;
        for (ModulePanel mp : components) {
            if(first){
                v.addContainerGap();
                first = false;
            } else
                v.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED);
            v.addComponent(mp,
                    GroupLayout.DEFAULT_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE);
        }
        v.addContainerGap(100, Short.MAX_VALUE);


        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(h)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(v)
        );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setPreferredSize(new java.awt.Dimension(224, 300));
        setLayout(new java.awt.GridLayout(getModulesCount(), 1, 0, 4));
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    private void addComponents(){
        for (Module module : modules) {
            add(new ModulePanel(module));
        }
    }

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized ApplicationTopComponent getDefault() {
        if (instance == null) {
            instance = new ApplicationTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the ApplicationTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ApplicationTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(ApplicationTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ApplicationTopComponent) {
            return (ApplicationTopComponent) win;
        }
        Logger.getLogger(ApplicationTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        p.setProperty("version", "1.0");
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    @Override
    public boolean canClose() {
        return false;
    }


}
